<?php

namespace app\model;

use think\facade\Log;
use think\Model;

class Node extends BaseModel
{
    /**
     * 获取节点数据
     * @param $ids
     * @return array
     */
    public function getAuthNodeByIds($ids)
    {
        try {

            if ($ids == '*') {
                $list = $this->order('sort desc')->select();
            } else {
                $list = $this->whereIn('id', $ids)->order('sort desc')->select();
            }
        } catch (\Exception $e) {
            Log::error('获取节点错误: ' . $e->getMessage() . PHP_EOL . $e->getTraceAsString());
            return dataReturn(-1, $e->getMessage());
        }

        return dataReturn(0, 'success', $list);
    }

    /**
     * 获取所有的菜单节点
     * @return array
     */
    public function getAllNode()
    {
        try {

            $list = $this->field('id,node_name as title,node_pid')->select();
        } catch (\Exception $e) {
            Log::error('获取所有节点错误: ' . $e->getMessage() . PHP_EOL . $e->getTraceAsString());
            return dataReturn(-1, $e->getMessage());
        }

        return dataReturn(0, 'success', $list);
    }

    /**
     * 根据path 获得信息
     * @param $component
     * @return array
     */
    public function getInfoByComponent($component)
    {
        try {

            $info = $this->where('component', $component)->find();
        } catch (\Exception $e) {
            Log::error('根据webPath获取信息错误: ' . $e->getMessage() . PHP_EOL . $e->getTraceAsString());
            return dataReturn(-1, $e->getMessage());
        }

        return dataReturn(0, 'success', $info);
    }

    /**
     * 添加节点数据并返回id
     * @param $param
     * @return array
     */
    public function addNodeReturnId($param)
    {
        try {

            $id = $this->insertGetId($param);
        } catch (\Exception $e) {
            Log::error('添加节点数据错误: ' . $e->getMessage() . PHP_EOL . $e->getTraceAsString());
            return dataReturn(-1, $e->getMessage());
        }

        return dataReturn(0, 'success', ['id' => $id]);
    }

    /**
     * 批量添加节点
     * @param $param
     * @return array
     */
    public function batchAddNode($param)
    {
        try {

            $this->insertAll($param);
        } catch (\Exception $e) {
            Log::error('批量添加节点数据错误: ' . $e->getMessage() . PHP_EOL . $e->getTraceAsString());
            return dataReturn(-1, $e->getMessage());
        }

        return dataReturn(0, 'success');
    }

    /**
     * 移除菜单
     * @param $id
     * @return array
     */
    public function removeMenuById($id)
    {
        try {

            $menuId = $this->field('id')->where('component', 'diy_' . $id)->find();

            $this->where('id', $menuId['id'])->whereOr('node_pid', $menuId['id'])->delete();
        } catch (\Exception $e) {
            Log::error('删除菜单错误: ' . $e->getMessage() . PHP_EOL . $e->getTraceAsString());
            return dataReturn(-1, $e->getMessage());
        }

        return dataReturn(0, 'success');
    }
}